package practiceProjects;

/**
 * 完成版，可从cmd调用
 * 之前的版本会出现存储在码表里面的词语为乱码的情况，
 * 因为cmd默认是GBK编码，而码表是以UTF-8格式存储的，
 * 经过几个失败的尝试，本程序是最终成功版。
 *
 * 修改点为：
 * 1.在BufferedReader封装的InputStreamReader里加入UTF-8参数，
 *      表示读取的为UTF-8格式字符，此前在bat文件里已使用`chcp 65001`设置为临时utf8格式；
 * 2.PrintWriter out = new PrintWriter(
 *                     new BufferedWriter(
 *                             new OutputStreamWriter(
 *                                     new FileOutputStream(path, true),
 *                                     StandardCharsets.UTF_8)))
 */

import java.io.*;
import java.nio.charset.StandardCharsets;

public class AddWordIntoRimeInUTF8 {

    public static boolean isValidLowerCase(String input) {
        return input != null && input.matches("^[a-z]+$");
    }

    public static void main(String[] args) {
        String path = "C:\\Users\\zhq11\\AppData\\Roaming\\Rime\\tigress.extended.dict.yaml";

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(System.in, "UTF-8"))) {

            System.out.println("input phrase:");
            String s = reader.readLine().trim();

            System.out.println("input code (0 < len <= 4):");
            String code = reader.readLine().trim();

            if (!isValidLowerCase(code) || code.isEmpty() || code.length() > 4) {
                System.out.println("invalid input, check your input.");
                return;
            }

            // 关键修改2：显式指定文件编码为UTF-8（原FileWriter默认GBK）
            try (PrintWriter out = new PrintWriter(
                    new BufferedWriter(
                            new OutputStreamWriter(
                                    new FileOutputStream(path, true),
                                    StandardCharsets.UTF_8)))) {

                String newPhrase = s + "\t" + code + "\t1000";
                out.println(newPhrase);
                System.out.println("add successful");

            } catch (IOException e) {
                System.err.println("file write failed: " + e.getMessage());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}